
<div class="profile-picture"
     style="text-align: center; overflow: hidden; width: 150px">
    <img id="entity_avatar"
         class="editable"
         alt="Avatar"
         style="height: 100%; width: 100%; display: inline;
                position: relative; left: 100%; margin-left: -200%"
         src="{%- if entity.thumbnail -%}
                /{{ entity.thumbnail.full_path }}
            {%- else -%}
                {{ request.static_url("stalker_pyramid:static/stalker/images/T_NO_IMAGE.gif") }}
            {%- endif -%}"/>
</div>

<script src='{{ request.static_url("stalker_pyramid:static/ace/js/jquery.gritter.min.js") }}'></script>

<script src='{{ request.static_url("stalker_pyramid:static/ace/js/jquery.ui.touch-punch.min.js") }}'></script>
<script type="text/javascript">

{% if has_permission('Update_'+entity.entity_type) %}
    $(document).ready(function () {

        $.fn.editable.defaults.mode = 'inline';

        try {//ie8 throws some harmless exception, so let's catch it

            //it seems that editable plugin calls appendChild, and as Image doesn't have it, it causes errors on IE at unpredicted points
            //so let's have a fake appendChild for it!

            var last_gritter
            $('#entity_avatar').editable({
                type: 'image',
                name: 'avatar',
                value: null,
                image: {
                    //specify ace file input plugin's options here
                    btn_choose: 'Change Avatar',
                    droppable: true,
                    /**
                     //this will override the default before_change that only accepts image files
                     before_change: function(files, dropped) {
return true;
},
                     */

                    //and a few extra ones here
                    name: 'file',//put the field name here as well, will be used inside the custom plugin
                    max_size: 11000000,//~100Kb
                    on_error: function (code) {//on_error function will be called when the selected file has a problem
                        if (last_gritter) $.gritter.remove(last_gritter);
                        if (code == 1) {//file format error
                            last_gritter = $.gritter.add({
                                title: 'File is not an image!',
                                text: 'Please choose a jpg|gif|png image!',
                                class_name: 'gritter-error gritter-center'
                            });
                        } else if (code == 2) {//file size rror
                            last_gritter = $.gritter.add({
                                title: 'File too big!',
                                text: 'Image size should not exceed 100Kb!',
                                class_name: 'gritter-error gritter-center'
                            });
                        }
                        else {//other error
                        }
                    },
                    on_success: function () {
                        $.gritter.removeAll();
                    }
                },
                url: function (params) {
                    //please modify submit_url accordingly
                    var submit_url = '/upload_files';
                    var deferred;


//if value is empty, means no valid files were selected
//but it may still be submitted by the plugin, because "" (empty string) is different from previous non-empty value whatever it was
//so we return just here to prevent problems
                    var value = $('#entity_avatar').next().find('input[type=hidden]:eq(0)').val();
                    if (!value || value.length == 0) {
                        deferred = new $.Deferred
                        deferred.resolve();
                        return deferred.promise();
                    }

                    var $form = $('#entity_avatar').next().find('.editableform:eq(0)')
                    var file_input = $form.find('input[type=file]:eq(0)');

//user iframe for older browsers that don't support file upload via FormData & Ajax
                    if (!("FormData" in window)) {
                        deferred = new $.Deferred

                        var iframe_id = 'temporary-iframe-' + (new Date()).getTime() + '-' + (parseInt(Math.random() * 1000));
                        $form.after('<iframe id="' + iframe_id + '" name="' + iframe_id + '" frameborder="0" width="0" height="0" src="about:blank" style="position:absolute;z-index:-1;"></iframe>');
                        $form.append('<input type="hidden" name="temporary-iframe-id" value="' + iframe_id + '" />');
                        $form.next().data('deferrer', deferred);//save the deferred object to the iframe
                        $form.attr({'method': 'POST', 'enctype': 'multipart/form-data',
                            'target': iframe_id, 'action': submit_url});

                        $form.get(0).submit();

                        //if we don't receive the response after 60 seconds, declare it as failed!
                        setTimeout(function () {
                            var iframe = document.getElementById(iframe_id);
                            if (iframe != null) {
                                iframe.src = "about:blank";
                                $(iframe).remove();

                                deferred.reject({'status': 'fail', 'message': 'Timeout!'});
                            }
                        }, 60000);
                    } else {
                        var fd = null;
                        try {
                            fd = new FormData($form.get(0));
                        } catch (e) {
                            //IE10 throws "SCRIPT5: Access is denied" exception,
                            //so we need to add the key/value pairs one by one
                            fd = new FormData();
                            $.each($form.serializeArray(), function (index,
                                                                     item) {
                                fd.append(item.name, item.value);
                            });
                            //and then add files because files are not included in serializeArray()'s result
                            $form.find('input[type=file]').each(function () {
                                if (this.files.length > 0) fd.append(this.getAttribute('name'), this.files[0]);
                            });
                        }

                        //if file has been drag&dropped , append it to FormData
                        if (file_input.data('ace_input_method') == 'drop') {
                            var files = file_input.data('ace_input_files');
                            if (files && files.length > 0) {
                                fd.append(file_input.attr('name'), files[0]);
                            }
                        }

                        console.log('fd:', fd);

                        deferred = $.ajax({
                            url: submit_url,
                            type: 'POST',
                            processData: false,
                            contentType: false,
                            dataType: 'json',
                            enctype: "multipart/form-data",
                            data: fd,
                            xhr: function () {
                                var req = $.ajaxSettings.xhr();
                                /*if (req && req.upload) {
                                 req.upload.addEventListener('progress', function(e) {
                                 if(e.lengthComputable) {
                                 var done = e.loaded || e.position, total = e.total || e.totalSize;
                                 var percent = parseInt((done/total)*100) + '%';
                                 //bar.css('width', percent).parent().attr('data-percent', percent);
                                 }
                                 }, false);
                                 }*/
                                return req;
                            },
                            beforeSend: function () {
                                //bar.css('width', '0%').parent().attr('data-percent', '0%');
                            },
                            success: function (data) {
                                // file is uploaded successfully
                                // and hopefully a link is created (data.link_ids[0])
                                // now attach it to this user as a thumbnail

                                $.post('/assign_thumbnail',
                                                $.param({
                                                    'link_ids': data.link_ids,
                                                    'entity_id': {{ entity.id }}
                                                })
                                        ).done(function (data1) {
                                            // and get back user data so we can now
                                            // where to set the current thumbnail
                                            // update the thumbnail


                                            $.getJSON('/entities/{{ entity.id }}/').done(function (data2) {

                                                var new_thumb_path = '/' + data2[0].thumbnail_full_path;
                                                $('#entity_avatar').attr('src', new_thumb_path);
                                                // also update side bar

                                            });
                                        });
                            }
                        });
                    }

                    deferred.done(function (res) {
                        console.log('code is here 1');
                        {#                    if (res.status == 'OK'){#}
                        {#                        $('#entity_avatar').get(0).src = res.url;#}
                        {#                    } else {#}
                        {#                        alert(res.message);#}
                        {#                    }#}
                        console.log('code is here 2');
                    }).fail(function (res) {
                                {#                    alert("Failure");#}
                            });

                    return deferred.promise();
                },

                success: function (response, newValue) {

                }
            })
        } catch (e) {
        }
    });

{% endif %}

</script>
